<?php

namespace App\Console\Commands;

use App\Models\Nft;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;

class UpdateNftHashRate extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:update-nft-hash-rate';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '更新NFT稀有度';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        bcscale(8);
        $directory = storage_path('app/public/nft_images/assets');
        try {
            // 检查目录是否存在
            if (!File::exists($directory)) {
                throw new \Exception("目录 {$directory} 不存在");
            }

            // 获取目录下所有.json文件
            $files = File::glob($directory . '/*.json');

            $backgrounds = [];
            $cores = [];
            $gears = [];
            $hats = [];
            $traits = [];
            $earrings = [];

            foreach ($files as $file) {
                // 读取文件内容
                $content = File::get($file);

                // 解析JSON
                $data = json_decode($content, true);

                // 验证JSON格式是否符合要求
                if ($this->validateJsonStructure($data)) {
                    $attributes = $data['attributes'];
                    foreach ($attributes as $attribute) {
                        if ($attribute['trait_type'] == 'Background') {
                            if (isset($backgrounds[$attribute['value']])) {
                                $backgrounds[$attribute['value']] += 1;
                            } else {
                                $backgrounds[$attribute['value']] = 1;
                            }
                            $background = $attribute['value'];
                        } elseif ($attribute['trait_type'] == 'Core') {
                            if (isset($cores[$attribute['value']])) {
                                $cores[$attribute['value']] += 1;
                            } else {
                                $cores[$attribute['value']] = 1;
                            }
                            $core = $attribute['value'];
                        } elseif ($attribute['trait_type'] == 'Gear') {
                            if (isset($gears[$attribute['value']])) {
                                $gears[$attribute['value']] += 1;
                            } else {
                                $gears[$attribute['value']] = 1;
                            }
                            $gear = $attribute['value'];
                        } elseif ($attribute['trait_type'] == 'Hat') {
                            if (isset($hats[$attribute['value']])) {
                                $hats[$attribute['value']] += 1;
                            } else {
                                $hats[$attribute['value']] = 1;
                            }
                            $hat = $attribute['value'];
                        } elseif ($attribute['trait_type'] == 'Traits') {
                            if (isset($traits[$attribute['value']])) {
                                $traits[$attribute['value']] += 1;
                            } else {
                                $traits[$attribute['value']] = 1;
                            }
                            $traitss = $attribute['value'];
                        } elseif ($attribute['trait_type'] == 'Earring') {
                            if (isset($earrings[$attribute['value']])) {
                                $earrings[$attribute['value']] += 1;
                            } else {
                                $earrings[$attribute['value']] = 1;
                            }
                            $earring = $attribute['value'];
                        } else {
                            $power = $attribute['value'];
                        }
                    }
                    //生成NFT
                    $nft = Nft::where('name', $data['name'])->first();
                    if (!$nft) {
                        $nft = new Nft();
                        $nft->user_id = 0;
                        $nft->nft_id = null;
                        $nft->name = $data['name'];
                        $nft->symbol = $data['symbol'];
                        $nft->description = $data['description'];
                        $nft->img = '/nft_images/assets/' . $data['image'];
                        $nft->background = $background;
                        $nft->core = $core;
                        $nft->gear = $gear;
                        $nft->hat = $hat;
                        $nft->traits = $traitss;
                        $nft->earring = $earring;
                        $nft->power = $power;
                        $nft->days = 365;
                        $nft->save();
                    }
                } else {
                    Log::warning("文件 {$file} 格式不符合要求", ['content' => $content]);
                }
            }
            $result = [
                'backgrounds' => $backgrounds,
                'cores' => $cores,
                'gears' => $gears,
                'hats' => $hats,
                'traits' => $traits,
                'earrings' => $earrings,
            ];
            $this->info('+++++++++++++++++count-json=========');
            $this->info(json_encode($result));
            File::put(app_path('nft/attribute_count.json'), json_encode($result, JSON_PRETTY_PRINT));
            foreach ($result as $key => $value) {
                foreach ($value as $k => $v) {
                    $result[$key][$k] = bcdiv($v, count($files), 8);
                }
            }
            $this->info('+++++++++++++++++percent-json=========');
            $this->info(json_encode($result));
            File::put(app_path('nft/attribute_percent.json'), json_encode($result, JSON_PRETTY_PRINT));
        } catch (\Exception $e) {
            Log::error("读取JSON文件失败: " . $e->getMessage());
            return [];
        }

        $nfts = Nft::all();
        foreach ($nfts as $nft) {
            $background_percent = $result['backgrounds'][$nft['background']] ?? 0;
            $core_percent = $result['cores'][$nft['core']] ?? 0;
            $gear_percent = $result['gears'][$nft['gear']] ?? 0;
            $hat_percent = $result['hats'][$nft['hat']] ?? 0;
            $traits_percent = $result['traits'][$nft['traits']] ?? 0;
            $earring_percent = $result['earrings'][$nft['earring']] ?? 0;
            $nft->background_percent = $background_percent;
            $nft->core_percent = $core_percent;
            $nft->gear_percent = $gear_percent;
            $nft->hat_percent = $hat_percent;
            $nft->traits_percent = $traits_percent;
            $nft->earring_percent = $earring_percent;
            $nft->percent = bcmul(bcmul(bcmul($background_percent,$core_percent), $gear_percent), bcmul($hat_percent, bcmul($traits_percent, $earring_percent)));
            $nft->save();
        }
    }

    /**
     * 验证JSON结构是否符合预期格式
     *
     * @param array $data
     * @return bool
     */
    protected function validateJsonStructure(array $data): bool
    {
        // 基本结构验证
        $requiredKeys = ['attributes', 'description', 'image', 'name'];
        foreach ($requiredKeys as $key) {
            if (!array_key_exists($key, $data)) {
                return false;
            }
        }

        // 验证attributes结构
        if (!is_array($data['attributes'])) {
            return false;
        }

        // 验证每个attribute项
        foreach ($data['attributes'] as $attribute) {
            if (!isset($attribute['trait_type']) || !isset($attribute['value'])) {
                return false;
            }
        }

        return true;
    }
}
